package dept

import (
	"context"
	"go-zero-project/common/excption"
	"go-zero-project/services/user/rpc/constans"
	"go-zero-project/services/user/rpc/internal/mapper"
	"go-zero-project/services/user/rpc/internal/mapper/bo"
	"go-zero-project/services/user/rpc/internal/svc"
	"go-zero-project/services/user/rpc/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type DeleteLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewDeptDeleteLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteLogic {
	return &DeleteLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *DeleteLogic) DeptDelete(in *pb.DeptDeleteReq) (*pb.EmptyObj, error) {
	// 判断是否有子部门
	deptMapper := mapper.NewDeptMapper()
	selectCount, err := deptMapper.SelectCount(l.svcCtx.DBEngin, bo.SysDeptBO{ParentId: in.DeptId})
	if err != nil {
		return nil, err
	}
	if selectCount < 0 {
		return nil, excption.NewErrCode(constans.DeleteMenuError)
	}
	// update role info
	updateErr := deptMapper.DeleteDept(l.svcCtx.DBEngin, in.DeptId)
	if updateErr != nil {
		return nil, updateErr
	}
	return &pb.EmptyObj{}, nil
}
